package com.cakeshop.servelt;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cakeshop.model.User;
import com.cakeshop.service.UserService;

/**
 * Servlet implementation class UserLoginServlet
 */
@WebServlet(name = "UserLoginServlet", value = "/user_login")
public class UserLoginServlet extends HttpServlet {
	
	private UserService uService = new UserService();

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String session_key = (String) request.getSession().getAttribute("KAPTCHA_SESSION_KEY");
		request.getSession().removeAttribute("KAPTCHA_SESSION_KEY");
		String ue = request.getParameter("ue");
		String password = request.getParameter("password");
		String code = request.getParameter("code");
		User user = uService.login(ue, password);
		if (session_key != null && session_key.equals(code)){
			if(user==null) {
				request.setAttribute("failMsg", "用户名、邮箱或者密码错误，请重新登录！");
				request.getRequestDispatcher("/user_login.jsp").forward(request, response);
			}else {
				request.getSession().setAttribute("user", user);
				TreeSet<Integer> likeSet = new TreeSet<>();
				TreeSet<Integer> noLikeSet = new TreeSet<>();
				request.getSession().setAttribute("likeSet", likeSet);
				request.getSession().setAttribute("noLikeSet", noLikeSet);
				request.getRequestDispatcher("/user_center.jsp").forward(request, response);
			}
		}else {
			response.getWriter().write("请不要重复提交！！！");
		}

	}
}
